package com.congee02.sw.var;

import java.util.*;

public class LongestEqualSubarray {

    public int longestEqualSubarray(List<Integer> nums, int k) {

        int n = nums.size();

        // 锚点
        List<Integer>[] poss = new List[n + 1];

        for (int i = 0 ; i < n ; i ++ ) {
            int x = nums.get(i);
            if (poss[x] == null) {
                poss[x] = new ArrayList<>();
            }
            poss[x].add(i);
        }

        int ans = 0;
        for (List<Integer> pos : poss) {

            if (pos.size() <= ans) {
                continue;
            }

            int l = 0;
            for (int r = 0 ; r < pos.size() ; r ++ ) {
                if (pos.get(r) - pos.get(l) - (r - l) > k) {
                    l ++;
                }   
                ans = Math.max(ans, r - l + 1);
            }

        }

        return ans;
    }

}
